import 'dart:convert';
import 'dart:ffi';

import 'package:flutter_demo/constants/constants.dart';
import 'package:flutter_demo/models/request/product.dart';
import 'package:flutter_demo/utils/storage.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';

import '../../http/product.dart';
import '../../models/category_model/category_model.dart';
import '../../models/product_model/product_model.dart';

class CategoryLogic extends GetxController {
  final RefreshController refreshController = RefreshController(initialRefresh: true);
  // 页码
  int _page = 1;

  // 页尺寸
  final int _limit = 20;


  // 列表-右侧数据
  List<ProductModel> items = [];


  // 分类导航数据-左侧数据
  List<CategoryModel> categoryItems = [];

  //分类id
  var categoryId = Get.arguments["id"];

  //初始化数据
  _initData() async{
    //读取缓存
    var stringCategories = Storage().getString(Constants.storageProductsCategories);
    categoryItems = stringCategories != "" ? jsonDecode(stringCategories).map<CategoryModel>((item) {
      return CategoryModel.fromJson(item);
    }).toList() : [];

    // 如果本地缓存空
    if (categoryItems.isEmpty) {
      categoryItems = await ProductApi.categories(); // 获取分类数据
    }
    update(["category"]);
  }


@override
  void onReady() {
    super.onReady();
    _initData();
  }

  //加载数据
  Future<bool> _loadSearch(bool isRefresh) async{
    //拉取数据
    var result = await ProductApi.products(ProductsReq(
      page: isRefresh ? 1 : _page,
      prePage: _limit,
      category: categoryId.toString()
    ));
    if(isRefresh){
      _page = 1;
      items.clear();
    }
    if(result.isNotEmpty){
      _page++;
      items.addAll(result);
    }
    return result.isEmpty;
  }

  //下拉刷新
  void onRefresh() async{
    try{
      await _loadSearch(true);
      refreshController.refreshCompleted();
    }catch(error){
      refreshController.refreshFailed();
    }
    update(["product_list"]);
  }
  //上拉加载更多
 void onLoading()async{
    if(items.isNotEmpty){
      try{
       var isEmpty = await _loadSearch(false);
       if(isEmpty){
         refreshController.loadNoData();
       }else{
         refreshController.loadComplete();
       }
      }catch(error){
        refreshController.loadFailed();
      }
    }else{
      refreshController.loadNoData();
    }
    update(["product_list"]);
 }

 @override
  void onClose() {
    super.onClose();
    refreshController.dispose();
  }

  // 分类点击事件
  void onCategoryTap(int id) async {
    categoryId = id;
    refreshController.requestRefresh();
    update(["left_nav"]);
  }


}
